<?php

namespace app\controller;

use app\BaseController;
use Exception;
use think\response\Json;

class Achievement extends BaseController
{
    /**
     * 获取总成就列表
     */
    public function getAchievementList(): Json
    {
        $uid = $this->getUid();
        if (empty($uid)) return pr(304, '请先登陆');
        try {
            $list = $this->M('achievement')->field('id,name,description,icon,state')->select();
            //state 为1时显示id name description icon state 为2时只显示id state
            $data = [];
            foreach ($list as $item) {
                if ($item['state'] == 2) {
                    $item = [
                        'id' => $item['id'],
                        'state' => $item['state']
                    ];
                }
                $data[] = $item;
            }
            return pr(200, '获取成功', $data);
        } catch (Exception $e) {
            return pr(500, $e->getMessage());
        }
    }
    /**
     * 获取用户成就列表
     */
    public function getUserAchievementList(): Json
    {
        $uid = $this->getUid();
        $uid = 1;
        if (empty($uid)) return pr(304, '请先登陆');
        $list = $this->M('achievement_user')->alias("au")->leftJoin("achievement a", "au.aid=a.id")->field("a.id,a.name,a.description,a.icon,a.state,au.time")->where(['au.uid' => $uid])->select();

        $data = [];
        foreach ($list as $item) {
            if ($item['state'] == 1) {
                $item = [
                    'id' => $item['id'],
                    'time' => $item['time'],
                ];
            }
            $data[] = $item;
        }
        return pr(200, '获取成功', $data);
    }
    /**
     * 申请获得成就
     */
    public function applyAchievement($id): Json
    {
        $uid = $this->getUid();
        if (empty($uid)) return pr(304, '请先登陆');
        try {
            $achievement = $this->M('achievement')->where(['id' => $id])->find();
            if (empty($achievement)) return pr(404, '成就不存在');
            $userAchievement = $this->M('achievement_user')->where(['uid' => $uid, 'aid' => $id])->find();
            if (!empty($userAchievement)) return pr(405, '已经申请过该成就');
            $this->M('achievement_user')->insert(['uid' => $uid, 'aid' => $id, 'time' => time()]);
            return pr(200, '申请成功');
        } catch (Exception $e) {
            return pr(500, $e->getMessage());
        }
    }
}